package com.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * 454. 四数相加 II
 * 两数组和存入Map然后再 双重循环另外两个数组查找
 *
 * @author fy
 * @date 2022/4/8 11:20
 */
public class Solution454 {

    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        int res = 0;
        if (nums1 == null || nums2 == null || nums3 == null || nums4 == null) {
            return res;
        }
        if (nums1.length == 0 || nums2.length == 0 || nums3.length == 0 || nums4.length == 0) {
            return res;
        }

        Map<Integer, Integer> sumMap = new HashMap<>();
        for (int num1 : nums1) {
            for (int num2 : nums2) {
                int sum = num1 + num2;
                sumMap.put(sum, sumMap.getOrDefault(sum, 0) + 1);
            }
        }

        for (int num3 : nums3) {
            for (int num4 : nums4) {
                int target = 0 - num3 - num4;
                if (sumMap.containsKey(target)) {
                    res += sumMap.get(target);
                }
            }
        }

        return res;
    }

}
